package config

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"log"
	"os"
)

var (
	ServerPort              string
	Mode                    string
	DBType                  string
	DBHost                  string
	DBPort                  int
	DBUser                  string
	DBPassword              string
	DBName                  string
	DBMaxOpenConnections    int
	DBMaxIdleConnections    int
	DBMaxConnectionLifeTime string
	URLHost                 string
	ProductPath             string
	AvatarPath              string
)

type ServerConfig struct {
	Port string `yaml:"port"`
	Mode string `yaml:"mode"`
}

type DatabaseConfig struct {
	DBType                  string `yaml:"type"`
	DBHost                  string `yaml:"host"`
	DBPort                  int    `yaml:"port"`
	DBUser                  string `yaml:"user"`
	DBPassword              string `yaml:"password"`
	DBName                  string `yaml:"dbname"`
	DBMaxOpenConnections    int    `yaml:"max_open_connections"`
	DBMaxIdleConnections    int    `yaml:"max_idle_connections"`
	DBMaxConnectionLifeTime string `yaml:"max_connection_lifetime"`
}

type PathConfig struct {
	Host        string `yaml:"Host"`
	ProductPath string `yaml:"ProductPath"`
	AvatarPath  string `yaml:"AvatarPath"`
}

type AppConfig struct {
	Server   ServerConfig   `yaml:"server"`
	Database DatabaseConfig `yaml:"database"`
	Path     PathConfig     `yaml:"path"`
}

// GlobalConfig 全局配置变量
var GlobalConfig AppConfig

func LoadConfig(path string) error {
	// 读取配置文件
	data, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	// 解析YAML
	err = yaml.Unmarshal(data, &GlobalConfig)
	if err != nil {
		return err
	}

	return nil
}

func init() {
	err := LoadConfig("E:\\openAPP\\GoLand 2023.3.8\\GoDemo\\my-systems\\pet-system\\configs\\config.yaml")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
		return
	}
	// 路由初始化
	ServerPort = GlobalConfig.Server.Port
	Mode = GlobalConfig.Server.Mode
	// 数据库初始化
	DBType = GlobalConfig.Database.DBType
	DBHost = GlobalConfig.Database.DBHost
	DBPort = GlobalConfig.Database.DBPort
	DBUser = GlobalConfig.Database.DBUser
	DBPassword = GlobalConfig.Database.DBPassword
	DBName = GlobalConfig.Database.DBName
	DBMaxOpenConnections = GlobalConfig.Database.DBMaxOpenConnections
	DBMaxIdleConnections = GlobalConfig.Database.DBMaxIdleConnections
	DBMaxConnectionLifeTime = GlobalConfig.Database.DBMaxConnectionLifeTime
	// 路径初始化
	URLHost = GlobalConfig.Path.Host
	ProductPath = GlobalConfig.Path.ProductPath
	AvatarPath = GlobalConfig.Path.AvatarPath

	fmt.Println("全局变量初始化成功...")
}
